import 'package:app/constants/http_constants.dart';
import 'package:app/http/api_service.dart';
import 'package:app/models/pagination.dart';
import 'package:app/models/project.dart';
import 'package:app/models/response.dart';
import 'package:app/router/index.dart';
import 'package:app/theme/design_tokens.dart';
import 'package:app/widgets/message.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:app/widgets/wrappers/liqui_pull_to_refresh_wrapper.dart';

class ProjectPage extends StatefulWidget {
  const ProjectPage({super.key});

  @override
  State<ProjectPage> createState() => _ProjectPageState();
}

class _ProjectPageState extends State<ProjectPage> {
  // 加载标记
  static const loadingTag = "##loading##";

  // 项目列表分页
  final Pagination _pagination = Pagination();

  // 项目列表数据
  List<Project> _projectList = [Project()..pjname = loadingTag];

  bool get hasMore => _projectList.length < _pagination.totalCount;

  @override
  void initState() {
    fetchGetProjectList();
    super.initState();
  }

  String formatTime(DateTime? value) {
    if (value == null) return "--";
    return formatDate(value, [yyyy, '-', mm, '-', dd]);
  }

  // 获取项目列表
  Future<void> fetchGetProjectList() async {
    ResponseData result =
        await ApiService(context, false).getProjectList(_pagination);
    if (result.code == HttpConstants.SUCCEED_CODE) {
      // 添加项目列表数据
      setState(() {
        _projectList.insertAll(
            _projectList.length - 1, result.data?.list ?? []);
      });
      // 设置分页信息
      _pagination.totalCount = result.data?.total ?? 0;
    }
  }

  // 重置项目列表
  void resetData() {
    _projectList = [Project()..pjname = loadingTag];
    _pagination.page = 1;
    _pagination.totalCount = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF6F8FC),
      appBar: AppBar(
        title: const Text("项目列表"),
        actions: [
          IconButton(
              onPressed: () async {
                bool? isFetch =
                    await router.push<bool>("/home/project/create_project");
                if (isFetch != null && isFetch) {
                  resetData();
                  fetchGetProjectList();
                }
              },
              icon: const Icon(Icons.add))
        ],
      ),
      body: LiquiPullToRefreshWrapper(
        onRefresh: () async {
          resetData();
          await fetchGetProjectList();
        }, // refresh callback
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: ListView.builder(
            itemCount: _projectList.length,
            itemBuilder: (context, index) {
              // 滑到底部
              if (_projectList[index].pjname == loadingTag) {
                if (hasMore) {
                  _pagination.page++;
                  fetchGetProjectList();
                  return Container(
                    alignment: Alignment.center,
                    padding: const EdgeInsets.all(16.0),
                    child: const SizedBox(
                        width: 24.0,
                        height: 24.0,
                        child: CircularProgressIndicator(
                          strokeWidth: 2.0,
                        )),
                  );
                } else {
                  return Container(
                    alignment: Alignment.center,
                    padding: const EdgeInsets.all(16.0),
                    child: const Text(
                      "没有更多数据",
                      style: TextStyle(color: Colors.grey),
                    ),
                  );
                }
              }
              return _buildItem(context, index);
            },
          ),
        ), // scroll view
      ),
    );
  }

  // 子项布局
  Widget _buildItem(BuildContext context, int index) {
    Project project = _projectList[index];
    Widget current = Stack(
      children: [
        Container(
            padding: const EdgeInsets.all(20),
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius:
                    BorderRadius.all(Radius.circular(DesignTokens.radius1))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    project.pjname!,
                    style: const TextStyle(fontSize: 17),
                  ),
                ),
                const SizedBox(
                  height: 18.5,
                ),
                Container(
                  width: double.infinity,
                  decoration: const BoxDecoration(
                      color: Color(0xFFF8FAFF),
                      borderRadius: BorderRadius.all(Radius.circular(4))),
                  padding:
                      const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
                  child: Wrap(
                    alignment: WrapAlignment.spaceBetween,
                    children: [
                      Text(
                        "创建人:${project.creater ?? "--"}",
                        style: const TextStyle(color: Color(0xFF999999)),
                      ),
                      Text(
                        "创建时间：${formatTime(project.createTime)}",
                        style: const TextStyle(color: Color(0xFF999999)),
                      )
                    ],
                  ),
                )
              ],
            )),
        Positioned(
          right: -2,
          top: 0,
          child: _buildProjectStatus(project.status),
        ),
      ],
    );

    return Padding(
      padding: const EdgeInsets.only(top: 12),
      child: current,
    );
  }

  // 项目状态组件
  Widget _buildProjectStatus(int? status) {
    // 项目状态 0未启动 1进行中 2已结束
    String statusText = "";
    BoxDecoration currentDecoration = const BoxDecoration();

    switch (status) {
      case 0:
        statusText = "未启动";
        currentDecoration = const BoxDecoration(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(20)),
            color: Color(0xFF94B1CE));
        break;
      case 1:
        statusText = "进行中";
        currentDecoration = const BoxDecoration(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(20)),
            gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Color(0xFFD0FE91), Color(0xFF00BBC0)]));
        break;
      case 2:
        statusText = "已结束";
        currentDecoration = const BoxDecoration(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
                bottomLeft: Radius.circular(20)),
            color: Color(0xFFCFCFCF));
        break;
      default:
        statusText = "未知状态";
        break;
    }

    Widget current = DecoratedBox(
      decoration: currentDecoration,
      child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8),
          child: Text(
            statusText,
            style: const TextStyle(
                color: Colors.white, fontSize: 11, fontWeight: FontWeight.w300),
          )),
    );

    return current;
  }
}
